package com.chen.common.satoken.provider;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.chen.root.annotation.OrderNum;
import com.chen.base.module.mybatis.mapper.CommonMapper;
import com.chen.common.satoken.enums.AuthTypeEnum;
import com.chen.common.satoken.params.LoginParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author: Long
 * @date: 2023/7/5 21:37
 **/
@OrderNum(10)
@Service
public class PasswordProvider extends AuthAbsProvider<LoginParam, String> {

    @Resource
    CommonMapper commonMapper;
    @Value("${sa-token.ex.aes-secret-key}")
    String secretKey;

    @Override
    public String authType() {
        return AuthTypeEnum.password.getType();
    }

    @Override
    public String loginId(LoginParam loginParam) {
        String sql = StrUtil.format("select * from auth_user where username = '{}'",
                authParamMap.get("username"));
        Map<String, Object> userMap = commonMapper.getOne(sql);
        Assert.notNull(userMap,"用户名或密码错误! ");

        // aes解密
        String password = SaSecureUtil.aesDecrypt(secretKey, userMap.get("password").toString());
        Assert.isTrue(password.equals(authParamMap.get("password")),"用户名或密码错误! ");

        return userMap.get("user_id").toString();
    }
}
